package com.yuexun.dhdoctor.module.commun.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;


import com.yuexun.dhdoctor.R;
import com.yuexun.dhdoctor.base.BaseEntity;
import com.yuexun.dhdoctor.base.BaseKJActivity;
import com.yuexun.dhdoctor.baselistener.OnDataBackListener;
import com.yuexun.dhdoctor.config.AppConfig;
import com.yuexun.dhdoctor.module.Contract.adapter.AddMemberAdapter;
import com.yuexun.dhdoctor.module.Contract.adapter.CreateGroupAdapter;
import com.yuexun.dhdoctor.module.Contract.adapter.DepartmentListAdapter;
import com.yuexun.dhdoctor.module.Contract.bean.DepartOrPeopleData;
import com.yuexun.dhdoctor.module.Contract.bean.GroupDataBean;
import com.yuexun.dhdoctor.module.Contract.bean.People;
import com.yuexun.dhdoctor.module.Contract.bean.UsersBean;
import com.yuexun.dhdoctor.module.Contract.model.impl.DepartmentModel;
import com.yuexun.dhdoctor.module.Contract.presenter.impl.DepartmentPresenter;
import com.yuexun.dhdoctor.module.Contract.ui.view.IDepartmentView;
import com.yuexun.dhdoctor.widget.EmptyLayout;
import com.yuexun.dhdoctor.widget.FixedSwipeListView;

import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * Created by Administrator on 2017/4/11 0011.
 */

public class Act_Department extends BaseKJActivity implements IDepartmentView {
    @Bind(R.id.title_tv)
    TextView titleTv;
    @Bind(R.id.etSearch2)
    EditText etSearch2;
    @Bind(R.id.btnSearchClear)
    ImageButton btnSearchClear;
    @Bind(R.id.searchLayout)
    LinearLayout searchLayout;
    @Bind(R.id.search_view)
    FrameLayout searchView;
    @Bind(R.id.dept_list)
    FixedSwipeListView deptList;
    @Bind(R.id.people_list)
    FixedSwipeListView peopleList;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;
    @Bind(R.id.grid)
    GridView grid;
    @Bind(R.id.addmember_sure_btn)
    TextView addmemberSureBtn;
    @Bind(R.id.search_hint)
    TextView searchHint;

    private Handler handler;
    ArrayList<People> usersBeans_origin = new ArrayList<>();
    ArrayList<People> peoples = new ArrayList<>();
    OnDataBackListener listener;

    private DepartmentPresenter presenter;
    public DepartmentListAdapter adapter_dept;
    private AddMemberAdapter addMemberAdapter;
    //    private BaseEntity<GroupDataBean> groupBean;
    CreateGroupAdapter adapter;

    int hospitalId;
    int type = 0;//0 finish 1 back
    GroupDataBean groupDataBean;
    List<GroupDataBean> datas;
    ArrayList<GroupDataBean> departmentBeans = new ArrayList<>();

    //0：不能选择自己  1：能选择
    private int isSelectMe;

    @Override
    public void setRootView() {
        super.setRootView();
        setContentView(R.layout.act_choice_department);
        ButterKnife.bind(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initData() {
        initView();
        initHandle();
        searchHint.setText("请输入部门名称、拼音");
        departmentBeans = (ArrayList<GroupDataBean>) getIntent().getExtras().getSerializable("departmentBeans");
        isSelectMe = getIntent().getExtras().getInt("isSelectMe", 0);
        presenter = new DepartmentPresenter(new DepartmentModel(), this);
        setGridView();

        hospitalId = PreferenceHelper.readInt(aty, AppConfig.USER_INFO, AppConfig.HOSPITALID);
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuid", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("hospId", hospitalId + "");
        presenter.getAllDepartment(params);

    }

    void initView() {

        emptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                emptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
            }
        });

        deptList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                type = 1;
                refresh(datas.get(position));
            }
        });

        etSearch2.addTextChangedListener(new TextWatcher() {
            boolean hasPadding = true;

            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence s, int i, int i1, int i2) {
                if (TextUtils.isEmpty(s) && !hasPadding) {
                    Message msg = new Message();
                    msg.what = 10002;
                    handler.sendMessage(msg);

                    hasPadding = true;
                } else if (!TextUtils.isEmpty(s) && hasPadding) {
                    Message msg = new Message();
                    msg.what = 10001;
                    handler.sendMessage(msg);

                    hasPadding = false;
                }

                if (adapter_dept != null) {
                    adapter_dept.getMyFilter(null == s ? "" : s.toString(), datas);
                }

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (etSearch2.getText().toString().length() == 0) {
                    searchLayout.setVisibility(View.VISIBLE);
//                    deptList.setVisibility(View.VISIBLE);
                } else {
//                    deptList.setVisibility(View.GONE);
                    searchLayout.setVisibility(View.GONE);
                }
            }
        });

    }

    void initHandle() {
        handler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 10001: // 搜索有文字的的时候
                        btnSearchClear.setVisibility(View.VISIBLE);
                        break;
                    case 10002: // 搜索没文字的的时候
                        btnSearchClear.setVisibility(View.INVISIBLE);
                        break;
                    case 10003:
                        setGridView();
                        break;
                    default: // 默认消息处理

                        break;
                }
            }
        };
    }

    @Override
    @OnClick({R.id.dept_back, R.id.addmember_sure_btn, R.id.btnSearchClear})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.dept_back:
                onBackPressed();
                break;
            case R.id.addmember_sure_btn:
                Bundle bundle = new Bundle();
                Intent intent = new Intent();
                bundle.putSerializable("departmentBeans", departmentBeans);
                intent.putExtras(bundle);
                setResult(10001, intent);
                finish();
                break;
            case R.id.btnSearchClear:
                etSearch2.setText("");
                break;
        }
    }

    @Override
    public void showGroupDatas(BaseEntity<GroupDataBean> groupBean) {
        if ("200".equals(groupBean.getStatus())) {
            groupDataBean = groupBean.getDatas().get(0).getChildDepartments().get(0);
            refresh(groupDataBean);
        } else {
            ViewInject.toast("获取数据失败");
        }
    }

    private void refresh(GroupDataBean groupDataBean) {
        emptyLayout.dismiss();
        datas = groupDataBean.getChildDepartments();
        List<UsersBean> usersBeen = groupDataBean.getUsers();

        if (datas != null && datas.size() > 0) {
            searchView.setVisibility(View.VISIBLE);
        } else {
            searchView.setVisibility(View.GONE);
        }

        adapter_dept = new DepartmentListAdapter(aty, datas, departmentBeans, handler, true,isSelectMe);
        deptList.setAdapter(adapter_dept);

        peoples.clear();
        for (int i = 0; i < usersBeen.size(); i++) {
            People people = new People();
            people.setUserId(usersBeen.get(i).getUser_id());
            people.setUserName(usersBeen.get(i).getUser_name());
            people.setJobNum(usersBeen.get(i).getJobNum());
            people.setPinyin(usersBeen.get(i).getPinyin());
            peoples.add(people);
        }
        addMemberAdapter = new AddMemberAdapter(getBaseContext(), peoples, usersBeans_origin, handler, 0, peopleList, true);
        peopleList.setAdapter(addMemberAdapter);

        if (type == 1) {
            titleTv.setText(groupDataBean.getDepartment_name());
        } else {
            titleTv.setText("部门处理");
        }
    }

    private void setGridView() {
        int size = departmentBeans.size();

        List<DepartOrPeopleData> datas = new ArrayList<>();
        for (GroupDataBean childDepartmentsBean : departmentBeans) {
            DepartOrPeopleData data = new DepartOrPeopleData();
            data.setDataId(childDepartmentsBean.getDepartment_id() + "");
            data.setDataName(childDepartmentsBean.getDepartment_name());
            datas.add(data);
        }

        if (size == 0) {
            addmemberSureBtn.setBackgroundResource(R.color.line);
            addmemberSureBtn.setEnabled(false);
        } else {
            addmemberSureBtn.setBackgroundResource(R.color.app_theme_color);
            addmemberSureBtn.setEnabled(true);
        }

        addmemberSureBtn.setText("确认");

        int length = 80;

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        float density = dm.density;
        int gridviewWidth = (int) (size * (length + 4) * density);
        int itemWidth = (int) (length * density);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                gridviewWidth, LinearLayout.LayoutParams.FILL_PARENT);
        grid.setLayoutParams(params); // 重点
        grid.setColumnWidth(itemWidth); // 重点
        grid.setHorizontalSpacing(5); // 间距
        grid.setStretchMode(GridView.NO_STRETCH);
        grid.setNumColumns(size); // 重点

        adapter = new CreateGroupAdapter(grid, datas, R.layout.item_send_addmember);
        grid.setAdapter(adapter);
    }

    @Override
    public void onBackPressed() {
        if (type == 1) {
            type = 0;
            refresh(groupDataBean);
        } else {
            finish();
        }
    }
}
